package dao

import (
	"fmt"
	"service/app/dto"
	"service/app/mode"
)

type CostDao struct {
	BaseDao
}

var costDao *CostDao

func CostDaoInit() *CostDao {
	if costDao == nil {
		return &CostDao{
			BaseDao: newBaseDao(),
		}
	}
	return costDao
}

func (m *CostDao) CostDelD(id *dto.ReqUriIdDto) error {
	return m.Orm.Delete(&mode.Db_cost{}, id.Id).Error
}
func (m *CostDao) CostSearchTimeD(acTime *dto.ReqUriTime, searchRang int) (*[]mode.Db_cost, error) {
	var costList []mode.Db_cost
	// 计算结束日期（一个月后）
	endDate := acTime.StartDate.AddDate(0, searchRang, 0)
	err := m.Orm.Model(&mode.Db_cost{}).Where("Record_time BETWEEN  ? AND ? ", acTime.StartDate, endDate).Find(&costList).Error
	if err != nil {
		return nil, err
	}
	return &costList, nil
}

func (m *CostDao) CostEditD(id *dto.ReqUriIdDto, costAc *dto.CostAddDto) error {
	var costDb mode.Db_cost
	err := m.Orm.Model(&mode.Db_cost{}).Where("id = ?", id.Id).Find(&costDb).Error
	if err != nil || costDb.ID == uint(0) {
		return fmt.Errorf("未找到Id为:%v,错误 %v", id.Id, err)
	}
	costAc.ConverCost(&costDb)
	if err := m.Orm.Save(&costDb).Error; err != nil {
		return fmt.Errorf("写入数据失败:%v,错误 %v", id.Id, err)
	}
	return nil
}

func (m *CostDao) CostAllD() (*[]mode.Db_cost, error) {
	var costList []mode.Db_cost
	err := m.Orm.Model(&mode.Db_cost{}).Find(&costList).Error
	if err != nil {
		return nil, err
	}
	return &costList, nil
}
func (m *CostDao) CostAddD(ac *mode.Db_cost) error {
	return m.Orm.Save(ac).Error
}
